package com.netty.client;
import com.netty.protocol.RpcDecoder;
import com.netty.protocol.RpcEncoder;
import com.netty.protocol.RpcRequest;
import com.netty.protocol.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * NettyClient
 * @author Gao
 */
public class NettyClient {

    private final String host;
    private final int port;
    private Channel channel;

    /**
     * 连接服务端的端口号地址和端口号
     * @param host
     * @param port
     */
    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        final EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();
        // 使用NioSocketChannel来作为连接用的channel类
        b.group(group).channel(NioSocketChannel.class)
                // 绑定连接初始化器
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    System.out.println("正在连接中...");
                    // 一个Channel包含一个ChannelPipeline，所有ChannelHandler都会注册到ChannelPipeline中，并按顺序组织起来。
                    // channel事件消息在ChannelPipeline中流动和传播，相应的事件能够被ChannelHandler拦截处理、传递、忽略或者终止。
                    ChannelPipeline pipeline = ch.pipeline();
                    //编码request
                    pipeline.addLast(new RpcEncoder(RpcRequest.class));
                    //解码response
                    pipeline.addLast(new RpcDecoder(RpcResponse.class));
                    //客户端处理类
                    pipeline.addLast(new ClientHandler());
                }
            });
        //发起异步连接请求，绑定连接端口和host信息
        final ChannelFuture future = b.connect(host, port).sync();

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture arg0) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("连接服务器成功");
                } else {
                    System.out.println("连接服务器失败");
                    //关闭线程组
                    group.shutdownGracefully();
                }
            }
        });
        this.channel = future.channel();
    }

    public Channel getChannel() {
        return channel;
    }
}
